/***********************************************
 @Name :        小谭老师
 @Time :        2025-2-22
 @Email :       tan.zhipeng@outlook.com
 @Comment :     功能窗口 智能视觉
 @FileName :    widget_funcb_smart_vision.cpp
 @Version :     1.0
************************************************/

#include "widget_funcb_smart_vision.h"
#include "ui_widget_funcb_smart_vision.h"
#include <QDebug>
#include <QUrlQuery>
#include <QBuffer>
#include <QJsonArray>
#include <QScrollArea>
#include <QButtonGroup>

Widget_funcB_Smart_vision::Widget_funcB_Smart_vision(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcB_Smart_vision)
{
    ui->setupUi(this);
    
    // 设置识别内容
    QVBoxLayout *vLayout_menug=new QVBoxLayout(ui->widget_menu);
    imgButton=new QPushButton(this);
    aniButton=new QPushButton(this);
    imgButton->setText("车牌识别");
    aniButton->setText("动物识别");
    vLayout_menug->addWidget(imgButton);
    vLayout_menug->addWidget(aniButton);
    vLayout_menug->addStretch();
    
    QString pushButtonStyle=R"(
    QPushButton {
        min-width: 80px;   /* 最小宽度 */
        min-height: 30px;  /* 最小高度 */
        background-color: #4CAF50; /* 背景颜色 */
        border: none;
        color: white;
        padding: 6px 6px;
        text-align: center;
        text-decoration: none;
        font-size: 20px;
        margin: 6px 6px;
        border-radius: 8px; /* 圆角 */
    }
    QPushButton:hover {
        background-color: #0099ff; /* 鼠标悬停时的颜色 */
    }
    QPushButton:checked {
        background-color: #0099ff;  /* 选中时的蓝色 */
    }
    )";
    imgButton->setCheckable( true) ;
    aniButton->setCheckable( true) ;
    QButtonGroup *buttonGroup = new QButtonGroup( this) ;
    buttonGroup->addButton( imgButton, 1) ;  // 参数1是按钮指针，参数2是自定义ID（ 可选） 
    buttonGroup->addButton( aniButton, 2) ;
    imgButton->setStyleSheet(pushButtonStyle);
    aniButton->setStyleSheet(pushButtonStyle);
    
    QVBoxLayout *vLayout_img=new QVBoxLayout(ui->widget_Img);
    vLayout_img->setAlignment(Qt::AlignCenter);
    img=new QLabel(this);
    img->setText("你还没有上传文件!");
    img->setScaledContents(true);
    vLayout_img->addWidget(img);
    
    QVBoxLayout *vLayout_widget_result=new QVBoxLayout(ui->widget_result);
    vLayout_widget_result->setMargin(0);
    vLayout_widget_result->setAlignment(Qt::AlignCenter);
    QScrollArea *area=new QScrollArea(ui->widget_result);
    vLayout_widget_result->addWidget(area);
    QWidget *content=new QWidget(area);
    content->setStyleSheet("background: transparent;border: none;");
    area->setFixedSize(450,100);
    area->setWidgetResizable(true);
    QVBoxLayout *vLayout_res=new QVBoxLayout(content);
    vLayout_res->setMargin(0);
    QLabel *res_label=new QLabel(content);
    res=new QLabel(content);
    res_label->setText("识别结果:");
    res_label->setFont(QFont("楷体",16,1));
    res->setFont(QFont("楷体",12,1));
    res->setScaledContents(true);
    res_label->setScaledContents(true);
    vLayout_res->addWidget(res_label);
    vLayout_res->addWidget(res);
    
    area->setStyleSheet(R"(
        QScrollArea{
        background: transparent;
        border: none;
        }

        // 简约垂直滚动条
        QScrollBar:vertical {
           border: none;
           background: #f0f2f5;
           width: 6px;
           margin: 0px 0px 0px 0px;
           border-radius: 3px;
        }
        
        QScrollBar::handle:vertical {
           background: #c2c7d0;
           border-radius: 3px;
           min-height: 30px;
        }
        
        QScrollBar::handle:vertical:hover {
           background: #a8aeb8;
        }
        
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
           height: 0px;
           background: none;
        }
        
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
           background: none;
        }
    )");
    area->setWidget(content);
    
    QVBoxLayout *vLayout=new QVBoxLayout(ui->widget_button);
    // 上传图片
    loadButton=new QPushButton(this);
    loadButton->setText("上传图片");
    // 识别
    uploadButton=new QPushButton(this);
    uploadButton->setText("识别图片");
    vLayout->addWidget(loadButton);
    vLayout->addWidget(uploadButton);
    loadButton->setStyleSheet(pushButtonStyle);
    uploadButton->setStyleSheet(pushButtonStyle);
    
    manager = new QNetworkAccessManager(this);
    
    connect(imgButton, &QPushButton::clicked, this,[&](){
        // 图像识别
        recType=IMG_RECOGNITION;
    });
    connect(aniButton, &QPushButton::clicked, this,[&](){
        // 动物识别
        recType=ANIMAL_RECOGNITION;
    });
    connect(manager, &QNetworkAccessManager::finished, this, &Widget_funcB_Smart_vision::handleNetworkReply);
    connect(loadButton, &QPushButton::clicked, this, [&](){
        switch (recType) {
        case IMG_RECOGNITION:{
            
        } 
        case ANIMAL_RECOGNITION:{
            // 上传图片
            QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                            "C:/Users/29008/Pictures/Camera Roll",
                                                            tr("Images (*.png *.xpm *.jpg *.webp)"));
            if(fileName==""){
                img->setText("你还没有上传文件!");
                res->setText("");
                return;
            }
            // 加载图片文件
            img->setPixmap(QPixmap(fileName));
            QImage image(fileName);
            if (image.isNull()) {
                qDebug() << "无法加载图片！";
                return;
            }
            // 将图片转换为字节数组（指定格式和质量）
            QByteArray byteArray;
            QBuffer buffer(&byteArray);
            buffer.open(QIODevice::WriteOnly);
            image.save(&buffer, "JPG", 80);  // 格式：JPG、PNG等，质量：0-100
            // 转换为Base64编码
            QByteArray base64Data = byteArray.toBase64();
            base64Str=QUrl::toPercentEncoding(QString(base64Data));
        }
            break;
        default:
            break;
        }
        
        
    });
    connect(uploadButton, &QPushButton::clicked, this, [&](){
        // QNetworkReply *reply = netManager->get(request);
        // reply->setProperty("requestType", "lyric");
        switch (recType) {
        case IMG_RECOGNITION:{
            // 识别
            // 设置请求URL
            QUrl url("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate");
            QUrlQuery query;
            query.addQueryItem("access_token", "24.5712c367ffa79a9b8efb5171ab0a92f5.2592000.1756385102.282335-119639218");
            url.setQuery(query);
            QNetworkRequest request(url);
            
            // 构建表单格式的请求Body
            QUrlQuery postData;
            postData.addQueryItem("image", base64Str); // 图片的Base64字符串（必须URL编码过的）
            // multi_detect 检测多张牌照
            postData.addQueryItem("multi_detect", "true");
            QByteArray requestBody = postData.toString(QUrl::FullyEncoded).toUtf8();
            
            // 设置请求头
            request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
            // 发送post请求
            manager->post(request,requestBody);
        } 
            break;
        case ANIMAL_RECOGNITION:{
            // 设置请求URL
            QUrl url("https://aip.baidubce.com/rest/2.0/image-classify/v1/animal");
            QUrlQuery query;
            query.addQueryItem("access_token", "24.43abad3fd187df8bca92a948d6b4e8c0.2592000.1756449294.282335-119642730");
            url.setQuery(query);
            QNetworkRequest request(url);
            
            // 构建表单格式的请求Body
            QUrlQuery postData;
            postData.addQueryItem("image", base64Str); // 图片的Base64字符串（必须URL编码过的）
            QByteArray requestBody = postData.toString(QUrl::FullyEncoded).toUtf8();
            
            // 设置请求头
            request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
            // 发送post请求
            QNetworkReply *reply= manager->post(request,requestBody);
            // 设置自定义数据 用来区分不同的请求,以便响应函数接收处理
            reply->setProperty("requestID","animal");
        }
            break;
        default:
            break;
        }
        
    });
}

Widget_funcB_Smart_vision::~Widget_funcB_Smart_vision()
{
    delete ui;
}

void Widget_funcB_Smart_vision::handleNetworkReply(QNetworkReply *reply)
{
    // 响应处理
    QString id = reply->property("requestID").toString();
    if (reply->error() != QNetworkReply::NoError) {
        qDebug()<< "请求失败!";
        reply->deleteLater();
        return;
    }
    
    QByteArray replyByteArray=reply->readAll();
    QJsonDocument doc=QJsonDocument::fromJson(replyByteArray);
    if (!doc.isNull() && doc.isObject()) {
        QJsonObject rootObj = doc.object();
        
        if(id.compare("animal")==0){
            if (rootObj.contains("result")) {
                QJsonArray wordsArray = rootObj["result"].toArray();
                QString text="";
                for(auto word:wordsArray){
                    QJsonObject wordsResult=word.toObject();
                    // 检查number是否存在且为字符串
                    QString name = wordsResult["name"].toString();
                    QString score = wordsResult["score"].toString();
                    text+=name+" 置信度:"+score+"\n";
                    res->setText(text);
                }
                
            }else{
                qDebug()<<"没有这个对象";
            }
        }else{
            // 检查words_result是否存在且为对象
            if (rootObj.contains("words_result")) {
                QJsonArray wordsArray = rootObj["words_result"].toArray();
                QString text="";
                for(auto word:wordsArray){
                    QJsonObject wordsResult=word.toObject();
                    // 检查number是否存在且为字符串
                    if (wordsResult.contains("number") && wordsResult["number"].isString()) {
                        QString number = wordsResult["number"].toString();
                        QString color = wordsResult["color"].toString();
                        text+=number+" 车牌颜色:"+color+"\n";
                        res->setText(text);
                    }
                }
                
            }else{
                qDebug()<<"没有这个对象";
            }
        }
        
    } else {
        qDebug() << "JSON解析失败";
    }
}
